<script setup lang="ts">
import type { RelationEdge, RelationsFacet } from '#/api/resource-center/types';

import { computed, reactive, ref } from 'vue';

import { IconifyIcon } from '@vben/icons';

import { message } from 'ant-design-vue';

// Props
interface Props {
  relations?: RelationsFacet;
}

const props = defineProps<Props>();

// Emits
const emit = defineEmits<{
  update: [relations: RelationsFacet];
}>();

// 响应式数据
const relationModalVisible = ref(false);
const editingRelation = ref<null | RelationEdge>(null);
const propertyKeys = ref<Record<string, string>>({});

// 表单数据
const relationForm = reactive({
  from: '',
  to: '',
  kind: '',
  direction: 'UNIDIRECTIONAL',
  description: '',
  strength: 'MEDIUM',
  properties: {} as Record<string, string>,
});

// 模拟可用资源列表
const availableResources = ref([
  { id: 'res-room-pool', name: '房间池资源' },
  { id: 'res-therapist-pool', name: '技师池资源' },
  { id: 'res-equipment-pool', name: '设备池资源' },
  { id: 'cap-spa-service', name: 'SPA服务能力' },
  { id: 'cap-payment', name: '支付能力' },
]);

// 计算属性
const relations = computed(() => props.relations || { edges: [] });

// 方法
const getRelationKindColor = (kind: string) => {
  const colorMap: Record<string, string> = {
    DEPENDS_ON: 'red',
    CONTAINS: 'blue',
    BELONGS_TO: 'green',
    RELATES_TO: 'orange',
    IMPLEMENTS: 'purple',
    EXTENDS: 'cyan',
    COMPOSES: 'geekblue',
    AGGREGATES: 'lime',
  };
  return colorMap[kind] || 'default';
};

const getRelationKindLabel = (kind: string) => {
  const labelMap: Record<string, string> = {
    DEPENDS_ON: '依赖',
    CONTAINS: '包含',
    BELONGS_TO: '属于',
    RELATES_TO: '关联',
    IMPLEMENTS: '实现',
    EXTENDS: '扩展',
    COMPOSES: '组合',
    AGGREGATES: '聚合',
  };
  return labelMap[kind] || kind;
};

const getDirectionLabel = (direction: string) => {
  const labelMap: Record<string, string> = {
    UNIDIRECTIONAL: '单向',
    BIDIRECTIONAL: '双向',
  };
  return labelMap[direction] || direction;
};

const showAddRelationModal = () => {
  editingRelation.value = null;
  resetRelationForm();
  relationModalVisible.value = true;
};

const editRelation = (edge: RelationEdge) => {
  editingRelation.value = edge;
  relationForm.from = edge.from?.id || 'current';
  relationForm.to = edge.to?.id || '';
  relationForm.kind = edge.kind;
  relationForm.direction = edge.metadata?.direction || 'UNIDIRECTIONAL';
  relationForm.description = edge.metadata?.description || '';
  relationForm.strength = edge.metadata?.strength || 'MEDIUM';
  relationForm.properties = { ...edge.metadata?.properties };

  // 初始化属性键名映射
  propertyKeys.value = {};
  Object.keys(relationForm.properties).forEach((key) => {
    propertyKeys.value[key] = key;
  });

  relationModalVisible.value = true;
};

const saveRelation = () => {
  if (!relationForm.to || !relationForm.kind) {
    message.error('请填写目标资源和关系类型');
    return;
  }

  const newEdge: RelationEdge = {
    from:
      relationForm.from === 'current' ? undefined : { id: relationForm.from },
    to: { id: relationForm.to },
    kind: relationForm.kind,
    metadata: {
      description: relationForm.description || undefined,
      strength: relationForm.strength,
      direction: relationForm.direction,
      properties:
        Object.keys(relationForm.properties).length > 0
          ? relationForm.properties
          : undefined,
    },
  };

  const currentEdges = relations.value.edges || [];
  let newEdges: RelationEdge[];

  if (editingRelation.value) {
    // 编辑模式 - 找到并替换对应的边
    newEdges = currentEdges.map((edge) => {
      if (edge === editingRelation.value) {
        return newEdge;
      }
      return edge;
    });
  } else {
    // 新增模式
    newEdges = [...currentEdges, newEdge];
  }

  emit('update', { ...relations.value, edges: newEdges });
  message.success(editingRelation.value ? '关系更新成功' : '关系添加成功');
  relationModalVisible.value = false;
  resetRelationForm();
};

const cancelRelation = () => {
  relationModalVisible.value = false;
  resetRelationForm();
};

const resetRelationForm = () => {
  relationForm.from = '';
  relationForm.to = '';
  relationForm.kind = '';
  relationForm.direction = 'UNIDIRECTIONAL';
  relationForm.description = '';
  relationForm.strength = 'MEDIUM';
  relationForm.properties = {};
  propertyKeys.value = {};
};

const deleteRelation = (edge: RelationEdge) => {
  const newEdges = relations.value.edges?.filter((e) => e !== edge) || [];
  emit('update', { ...relations.value, edges: newEdges });
  message.success('关系删除成功');
};

// 属性编辑器方法
const addProperty = () => {
  const key = `property_${Date.now()}`;
  relationForm.properties[key] = '';
  propertyKeys.value[key] = key;
};

const removeProperty = (key: string) => {
  delete relationForm.properties[key];
  delete propertyKeys.value[key];
};

const updatePropertyKey = (oldKey: string) => {
  const newKey = propertyKeys.value[oldKey];
  if (newKey && newKey !== oldKey) {
    relationForm.properties[newKey] = relationForm.properties[oldKey];
    delete relationForm.properties[oldKey];
    propertyKeys.value[newKey] = newKey;
    delete propertyKeys.value[oldKey];
  }
};
</script>

<template>
  <div class="resource-relations">
    <!-- 关系管理头部 -->
    <div class="relations-header">
      <h3>关系管理</h3>
      <a-button type="primary" @click="showAddRelationModal">
        <template #icon>
          <IconifyIcon icon="ant-design:plus-outlined" />
        </template>
        添加关系
      </a-button>
    </div>

    <!-- 关系配置内容 -->
    <div class="relations-content">
      <a-empty v-if="!relations?.edges?.length" description="暂无关系定义" />

      <div v-else class="relations-list">
        <a-card
          v-for="edge in relations.edges"
          :key="`${edge.from?.id}-${edge.to?.id}-${edge.kind}`"
          class="relation-card"
          size="small"
        >
          <template #title>
            <div class="relation-title">
              <span class="source-resource">{{
                edge.from?.id || '当前资源'
              }}</span>
              <a-tag :color="getRelationKindColor(edge.kind)" size="small">
                {{ getRelationKindLabel(edge.kind) }}
              </a-tag>
              <span class="target-resource">{{ edge.to?.id }}</span>
            </div>
          </template>

          <div class="relation-info">
            <p v-if="edge.metadata?.description">
              <strong>描述:</strong> {{ edge.metadata.description }}
            </p>
            <p v-if="edge.metadata?.strength">
              <strong>强度:</strong> {{ edge.metadata.strength }}
            </p>
            <p v-if="edge.metadata?.direction">
              <strong>方向:</strong>
              {{ getDirectionLabel(edge.metadata.direction) }}
            </p>
          </div>

          <div class="relation-actions">
            <a-button type="link" size="small" @click="editRelation(edge)">
              编辑
            </a-button>
            <a-popconfirm
              title="确定要删除这个关系吗？"
              @confirm="deleteRelation(edge)"
            >
              <a-button type="link" size="small" danger>删除</a-button>
            </a-popconfirm>
          </div>
        </a-card>
      </div>
    </div>

    <!-- 关系图谱可视化 -->
    <div v-if="relations?.edges?.length" class="relations-graph">
      <a-card title="关系图谱">
        <div class="graph-container">
          <div class="graph-placeholder">
            <a-empty description="关系图谱可视化功能开发中..." />
            <p class="graph-info">
              当前共有 {{ relations.edges.length }} 个关系定义
            </p>
          </div>
        </div>
      </a-card>
    </div>

    <!-- 添加/编辑关系模态框 -->
    <a-modal
      v-model:open="relationModalVisible"
      :title="editingRelation ? '编辑关系' : '添加关系'"
      width="600px"
      @ok="saveRelation"
      @cancel="cancelRelation"
    >
      <a-form :model="relationForm" layout="vertical">
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="源资源" name="from">
              <a-select
                v-model:value="relationForm.from"
                placeholder="请选择源资源"
                show-search
                allow-clear
              >
                <a-select-option value="current">当前资源</a-select-option>
                <a-select-option
                  v-for="resource in availableResources"
                  :key="resource.id"
                  :value="resource.id"
                >
                  {{ resource.name }} ({{ resource.id }})
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="目标资源" name="to">
              <a-select
                v-model:value="relationForm.to"
                placeholder="请选择目标资源"
                show-search
                allow-clear
              >
                <a-select-option
                  v-for="resource in availableResources"
                  :key="resource.id"
                  :value="resource.id"
                >
                  {{ resource.name }} ({{ resource.id }})
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="关系类型" name="kind">
              <a-select
                v-model:value="relationForm.kind"
                placeholder="请选择关系类型"
              >
                <a-select-option value="DEPENDS_ON">依赖</a-select-option>
                <a-select-option value="CONTAINS">包含</a-select-option>
                <a-select-option value="BELONGS_TO">属于</a-select-option>
                <a-select-option value="RELATES_TO">关联</a-select-option>
                <a-select-option value="IMPLEMENTS">实现</a-select-option>
                <a-select-option value="EXTENDS">扩展</a-select-option>
                <a-select-option value="COMPOSES">组合</a-select-option>
                <a-select-option value="AGGREGATES">聚合</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="关系方向" name="direction">
              <a-select
                v-model:value="relationForm.direction"
                placeholder="请选择关系方向"
              >
                <a-select-option value="UNIDIRECTIONAL">单向</a-select-option>
                <a-select-option value="BIDIRECTIONAL">双向</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item label="关系描述" name="description">
          <a-textarea
            v-model:value="relationForm.description"
            placeholder="请输入关系描述"
            :rows="3"
          />
        </a-form-item>

        <a-form-item label="关系强度" name="strength">
          <a-select
            v-model:value="relationForm.strength"
            placeholder="请选择关系强度"
          >
            <a-select-option value="WEAK">弱</a-select-option>
            <a-select-option value="MEDIUM">中等</a-select-option>
            <a-select-option value="STRONG">强</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="关系属性" name="properties">
          <div class="properties-editor">
            <a-button @click="addProperty" type="dashed" block>
              <IconifyIcon icon="ant-design:plus-outlined" />
              添加属性
            </a-button>

            <div v-if="relationForm.properties" class="properties-list">
              <div
                v-for="(value, key) in relationForm.properties"
                :key="key"
                class="property-item"
              >
                <a-row :gutter="8">
                  <a-col :span="8">
                    <a-input
                      v-model:value="propertyKeys[key]"
                      placeholder="属性名"
                      @change="updatePropertyKey(key)"
                    />
                  </a-col>
                  <a-col :span="12">
                    <a-input
                      v-model:value="relationForm.properties[key]"
                      placeholder="属性值"
                    />
                  </a-col>
                  <a-col :span="4">
                    <a-button type="text" danger @click="removeProperty(key)">
                      <IconifyIcon icon="ant-design:delete-outlined" />
                    </a-button>
                  </a-col>
                </a-row>
              </div>
            </div>
          </div>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<style lang="less" scoped>
.resource-relations {
  .relations-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;

    h3 {
      margin: 0;
    }
  }

  .relations-content {
    .relations-list {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
      gap: 16px;
      margin-bottom: 16px;
    }

    .relation-card {
      .relation-title {
        display: flex;
        align-items: center;
        gap: 8px;

        .source-resource,
        .target-resource {
          font-weight: 500;
          color: #1890ff;
        }
      }

      .relation-info {
        margin-bottom: 8px;

        p {
          margin: 4px 0;
          font-size: 12px;
        }
      }

      .relation-actions {
        display: flex;
        gap: 4px;
      }
    }
  }

  .relations-graph {
    .graph-container {
      min-height: 300px;
      display: flex;
      align-items: center;
      justify-content: center;

      .graph-placeholder {
        text-align: center;

        .graph-info {
          margin-top: 16px;
          color: #666;
        }
      }
    }
  }

  .properties-editor {
    .properties-list {
      margin-top: 12px;

      .property-item {
        margin-bottom: 8px;
        padding: 8px;
        border: 1px solid #f0f0f0;
        border-radius: 4px;
        background: #fafafa;
      }
    }
  }
}
</style>
